/**
 * 功能：传二进制文件公共方法
 * 参数：file二进制参数数组，
 * 		fileUrl请求地址，
 * 		parameter附加参数,二进制流key 默认 'files',
 * 		fileShow判断文件是否必须传
 */
// #ifdef MP-WEIXIN
const FormData = require('./formData.js')
// #endif
function AllMethodFile({
	file,
	fileUrl,
	parameter = {},
	fileName = 'files',
	fileShow = false
}) {
	console.log(file, fileUrl, parameter, fileName, fileShow)
	if ((!Array.isArray(file) || file.length <= 0) && fileShow) {
		uni.showToast({
			title: '缺少二进制文档流',
			icon: 'none'
		})
		return
	}
	let baseUrl = baseMethod()
	if (!baseUrl.baseUrl || !fileUrl) {
		uni.showToast({
			title: '缺少请求地址',
			icon: 'none'
		})
		return
	}
	let token = uni.getStorageSync('accessToken')
	if (!token) {
		uni.showToast({
			title: '缺少token',
			icon: 'none'
		})
		return
	}
	// #ifdef APP || H5
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: `${baseUrl.baseUrl}${fileUrl}`,
			files: file,
			filePath: file.path, // 文件资源的路径
			formData: parameter,
			header: {
				'Authorization': 'Bearer ' + token
			},
			success: function(uploadFileRes) {
				// console.log(uploadFileRes, '444444444444444444444');
				let data = JSON.parse(uploadFileRes.data)
				resolve(data)
			},
			fail: function(errFile) {
				reject(errFile)
			},
			complete: function(res) {
				// console.log("11111111111111")
			},
		})
	})
	// #endif

	// #ifdef MP-WEIXIN
	let formData = new FormData();
	// 添加其余参数
	Object.entries(parameter).forEach(code => {
		const [key, value] = code
		formData.append(key, value);
	})
	// 二进制流
	if (Array.isArray(file) && file.length > 0) {
		file.forEach(code => {
			formData.appendFile(fileName, code.path);
		})
	}
	let data = formData.getData();
	return new Promise((resolve, reject) => {
		uni.request({
			url: `${baseUrl}${fileUrl}`,
			method: 'POST',
			data: data.buffer,
			header: {
				'content-type': data.contentType,
				'Authorization': 'Bearer ' + token
			},
			success: (res => {
				let data = res.data
				resolve(data)
			}),
			fail: (err) => {
				reject(err)
			}
		})
	})
	// #endif
}

function baseMethod() {
	let baseUrl = ''
	let authUrl = ''
	if (process.env.NODE_ENV === 'development') {
		// 测试环境
		baseUrl = "https://uni.epumping.com/proc/";
		// authUrl = "http://106.14.56.171:6001/";
		authUrl = "https://auth.epumping.com/";

	} else if (process.env.NODE_ENV === 'production') {
		// 生产环境
		baseUrl = "https://uni.epumping.com/proc/";
		authUrl = "https://auth.epumping.com/";
	}
	
	return {
		baseUrl,
		authUrl
	}
}
// code 图片类型
function ImgaeChoice(code) {
	return false
}
export {
	AllMethodFile,
	baseMethod,
	ImgaeChoice
}
